<?php

namespace App\Models;

class Logs extends BaseModel
{
    protected $table = 'logs';

    protected $partitionEnabled = true;  // 是否启用分表
    protected $partitionType = 'year';

    // 日志类型常量
    const LOG_TYPE_ACCESS = 'access';      // 访问日志
    const LOG_TYPE_OPERATION = 'operation'; // 操作日志
    const LOG_TYPE_CUSTOM = 'custom';       // 自定义日志

    /**
     * 获取表字段
     * @return array
     */
    protected function columns(): array
    {
        return [
            'id',
            'admin_id',
            'event_name',
            'content',
            'url',
            'query',
            'params',
            'response',
            'ip',
            'user_agent',
            'method',
            'module',
            'action',
            'log_type',
            'status_code',
            'response_time',
            'created_at',
            'updated_at',
            'deleted_at'
        ];
    }

    /**
     * 重写查询构造方法
     * @param array $params 查询参数
     * @return \Illuminate\Database\Eloquent\Builder
     */
    protected function buildQuery(array $params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = parent::buildQuery($params);
        // 按时间范围筛选
        if (!empty($params['start_time'])) {
            $query->where('created_at', '>=', strtotime($params['start_time']));
        }
        if (!empty($params['end_time'])) {
            $endTime = strtotime($params['end_time']) + 86400 - 1;
            $query->where('created_at', '<=', $endTime);
        }

        return $query;
    }
}
